//
//  XJEmojiKeyboardViewModel.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/27.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

class XJEmojiKeyboardViewModel: NSObject {
    
    /// 创建单例
    static let sharedEmojiViewModel: XJEmojiKeyboardViewModel = XJEmojiKeyboardViewModel()
    
    /// 最近表情归档路径
    private lazy var path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmoticon.archive")
    
    
    /// 表情bundle
   lazy var emotionBundle: NSBundle = {
        
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        
        return NSBundle(path: path)!
    }()
    
    // MARK: - 获取表情数据
    
    /// 最近表情
     lazy var recentEmotcons: [XJEmojiModel] = {
        
        if let res = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? [XJEmojiModel]{
            return res
        }else{
            
            return [XJEmojiModel]()
        }
    }()
    
    /// 默认表情数组
    private lazy var defaultEmotions: [XJEmojiModel] = {
        
        return self.emotionsWithPath("default/info.plist")
    }()
    /// emoji表情数组
    private lazy var emojiEmotions: [XJEmojiModel] = {
    
        return self.emotionsWithPath("emoji/info.plist")
    }()
    /// 浪小花
    private lazy var lxhEmotions: [XJEmojiModel] = {
        
        return self.emotionsWithPath("lxh/info.plist")
    }()
    
    /// 所有表情数据(三维数组)
     lazy var allEmotions: [[[XJEmojiModel]]] = {
    
        return[
        
            [self.recentEmotcons],
            self.emotionPageArr(self.defaultEmotions),
            self.emotionPageArr(self.emojiEmotions),
            self.emotionPageArr(self.lxhEmotions)
        ]
    }()
    
    /// 通过表情字符串找到其对应的表情模型
    func emoticonWithChs(chs: String) -> XJEmojiModel? {
        
        //遍历默认表情
        for value in defaultEmotions {
            if value.chs == chs{
                return value
            }
        }
        //遍历浪小花表情
        for value in lxhEmotions {
            if value.chs == chs {
            return value
            }
        }
        return nil
    }
    
    /**
     保存最近表情
     */
    
    func saveRecentEmoticon(emoticon: XJEmojiModel){
        
        var emoticons = allEmotions[0][0]
        
        // 取到的重复表情的数组
        let repeatEmoticon = emoticons.filter { (value) -> Bool in
            if value.type == emoticon.type {
                if value.type == "1" {
                    // emoji表情，对比code
                    return value.code == emoticon.code
                }else{
                    // 对比chs
                    return value.chs == emoticon.chs
                }
            }else{
                return false
            }
        }
        
        // 移除重复移
        for value in repeatEmoticon {
            if let index = emoticons.indexOf(value) {
                emoticons.removeAtIndex(index)
            }
        }
        // 1. 将传入的表情模型保存到当前的最近表情的数组里面去
        // self.recentEmoticons.append(emoticon)
        emoticons.insert(emoticon, atIndex: 0)
        
        // 2.  去掉多余20个的表情
        while emoticons.count > 20 {
            emoticons.removeLast()
        }
        
        allEmotions[0][0] = emoticons
        
        // 3. 使用归档的方法保存最近表情的数组
        NSKeyedArchiver.archiveRootObject(emoticons, toFile: path)
        
    }
    
    /**
     切割表情,分成页,每页最多20个
     */
    private func emotionPageArr(emotions: [XJEmojiModel])->([[XJEmojiModel]]) {
    
        //页数
        let pageCount = (emotions.count - 1)/20 + 1
        
        //遍历截取每页内容
        var resArr: [[XJEmojiModel]] = [[XJEmojiModel]]()
        for i in 0..<pageCount {
        
            let loc = 20 * i
            var length = 20
            
            //判断数组是否越界
            if loc + length > emotions.count {
                length = emotions.count - loc
            }
            
           let arr = (emotions as NSArray).subarrayWithRange(NSMakeRange(loc, length)) as! [XJEmojiModel]
            resArr.append(arr)
        }
        return resArr
    }
    
    /**
     通过路径获取对应的表情数据
     */
    private func emotionsWithPath(filePath: String?) -> [XJEmojiModel] {
    
        //取到默认表情文件路径
        let path = self.emotionBundle.pathForResource(filePath, ofType: nil)!
        
        //读取字典数组
        let dicts = NSArray(contentsOfFile: path)!
        
        //字典转模型,返回结果
        var tempArr = [XJEmojiModel]()
        
        for values in dicts {
            
            let model = XJEmojiModel(dict: values as! [String : AnyObject])
            
            //设置表情对应的文件夹路径
            let fileName = (filePath! as NSString).stringByDeletingLastPathComponent
            model.fileName = fileName
            tempArr.append(model)
        }
        
        return tempArr
    
    }
}
